<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="家庭名称" prop="familyName">
        <el-input
            v-model="queryParams.familyName"
            placeholder="请输入家庭名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

<!--      <el-form-item label="关联用户" prop="userId">-->
<!--        <el-select-->
<!--            v-model="queryParams.userId"-->
<!--            placeholder="请选择关联用户"-->
<!--            clearable-->
<!--            filterable-->
<!--            style="width: 240px"-->
<!--        >-->
<!--          <el-option-->
<!--              v-for="user in filteredUserOptions"-->
<!--              :key="user.userId"-->
<!--              :label="`${user.nickName} (ID:${user.userId})`"-->
<!--              :value="user.userId"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
                        v-model="queryParams.createdAt"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['airsystem:families:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['airsystem:families:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['airsystem:families:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="familiesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

<!--      <el-table-column label="家庭ID" align="center" prop="familyId" />-->
      <el-table-column
          label="序号"
          align="center"
          width="80"
          class-name="serial-number"
      >
        <template #default="scope">
    <span class="serial">
      {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
    </span>
        </template>
      </el-table-column>
      <el-table-column label="家庭名称" align="center" prop="familyName" />
      <el-table-column label="地址" align="center" prop="address" />

      <el-table-column label="关联用户" align="center" prop="userId">
        <template #default="scope">
          <span>{{ getUserName(scope.row.userId) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['airsystem:families:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['airsystem:families:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改家庭管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="familiesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="家庭名称" prop="familyName">
          <el-input v-model="form.familyName" placeholder="请输入家庭名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="关联用户" prop="userId">
          <el-select
              v-model="form.userId"
              placeholder="请选择关联用户"
              clearable
              filterable
              style="width: 100%"
          >
            <el-option
                v-for="user in filteredUserOptions"
                :key="user.userId"
                :label="`${user.nickName} (ID:${user.userId})`"
                :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
                          v-model="form.createdAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Families">
import { listFamilies, getFamilies, delFamilies, addFamilies, updateFamilies } from "@/api/airsystem/families";
import { listUser } from "@/api/system/user";
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';

const { proxy } = getCurrentInstance();

const familiesList = ref([]);
const userOptions = ref([]);
const filteredUserOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    familyName: null,
    address: null,
    userId: null,
    createdAt: null
  },
  rules: {
    familyName: [
      { required: true, message: "家庭名称不能为空", trigger: "blur" }
    ],
    address: [
      { required: true, message: "地址不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "请选择关联用户", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 获取用户列表并过滤 */
async function getUserList() {
  try {
    loading.value = true;
    const response = await listUser();
    userOptions.value = response.rows || [];
    // 过滤掉id=1的用户
    filteredUserOptions.value = userOptions.value.filter(
        user => user.userId != 1
    );
  } catch (error) {
    console.error("获取用户列表失败:", error);
    proxy.$modal.msgError("获取用户列表失败");
  } finally {
    loading.value = false;
  }
}

/** 根据用户ID获取用户名 */
function getUserName(userId) {
  const user = userOptions.value.find(user => user.userId == userId);
  return user ? `${user.nickName} (ID:${user.userId})` : userId;
}

/** 查询家庭管理列表 */
async function getList() {
  try {
    loading.value = true;
    const response = await listFamilies(queryParams.value);
    familiesList.value = response.rows;
    total.value = response.total;
  } catch (error) {
    console.error("获取家庭列表失败:", error);
    proxy.$modal.msgError("获取家庭列表失败");
  } finally {
    loading.value = false;
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    familyId: null,
    familyName: null,
    address: null,
    userId: null,
    createdAt: null
  };
  proxy.resetForm("familiesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.familyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加家庭管理";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  try {
    reset();
    const _familyId = row.familyId || ids.value;
    const response = await getFamilies(_familyId);
    form.value = response.data;
    open.value = true;
    title.value = "修改家庭管理";
  } catch (error) {
    console.error("获取家庭详情失败:", error);
    proxy.$modal.msgError("获取家庭详情失败");
  }
}

/** 提交按钮 */
async function submitForm() {
  try {
    const valid = await proxy.$refs["familiesRef"].validate();
    if (valid) {
      if (form.value.familyId != null) {
        await updateFamilies(form.value);
        proxy.$modal.msgSuccess("修改成功");
      } else {
        await addFamilies(form.value);
        proxy.$modal.msgSuccess("新增成功");
      }
      open.value = false;
      getList();
    }
  } catch (error) {
    console.error("提交表单失败:", error);
  }
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    const _familyIds = row.familyId || ids.value;
    await proxy.$modal.confirm(`是否确认删除家庭管理编号为"${_familyIds}"的数据项？`);
    await delFamilies(_familyIds);
    getList();
    proxy.$modal.msgSuccess("删除成功");
  } catch (error) {
    console.error("删除记录失败:", error);
  }
}



// 组件挂载时初始化
onMounted(() => {
  getUserList();
  getList();
});
</script>
